package com.second.app.proxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @Author GYZ
 * @Date 2023/9/18
 * <pre>
 *
 * </pre>
 */
public class CglibDynamicProxy implements MethodInterceptor {


    private Object target;

    public CglibDynamicProxy(Object target) {
        this.target = target;
    }

    public Object getProxy(){
        Enhancer enhancer = new Enhancer();

        enhancer.setSuperclass(target.getClass());

        enhancer.setCallback(this);

        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {

        System.out.println("【记录日志】准备执行方法："+method.getName()+"，参数列表："+ Arrays.toString(args));

        Object result = method.invoke(target, args);

        System.out.println("【记录日志】方法执行结束："+method.getName()+"，返回值为："+ result);

        return result;
    }
}
